package MapAndSet.BinarySearchTree;

public class BinarySearchTree {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;
        public TreeNode(int val) {
            this.val = val;
        }
    }

    public TreeNode root = null;

    public boolean search(int val) {
        TreeNode cur = root;
        while(cur!=null){
            if(cur.val > val){
                cur = cur.left;
            }else if(cur.val < val) {
                cur = cur.right;
            }else{
                return true ;
            }
        }
        return false;
    }

    public void insert(int val) {
        TreeNode node = new TreeNode(val);
        if(root==null){
            root=node;
            return;
        }
        TreeNode cur = root;
        TreeNode parent = null;
        while(cur!=null){
            parent = cur;
            if(cur.val>val){
                cur=cur.left;
            }else if(cur.val<val){
                cur=cur.right;
            }else{
                return;
            }
        }
        if(parent.val>val){
            parent.left = node;
        }else if(parent.val<val) {
            parent.right = node;
        }
    }

    public void remove(int val){
        if(root==null){
            return;
        }
        TreeNode cur = root;
        TreeNode parent = null;
        while(cur!=null) {
            if(cur.val>val){
                parent=cur;
                cur=cur.left;
            }else if(cur.val<val){
                parent=cur;
                cur=cur.right;
            }else{
                removeNode(parent,cur);
            }
        }
    }

    private void removeNode(TreeNode parent,TreeNode cur) {
        if(cur.left == null) {//以cur为根左树为空的情况
            if(cur==root){//parent和cur在一起（顶根为要删除的节点时）
                root=cur.right;
            }else if(cur==parent.left){//cur为要删除元素并且走到了parent左边，cur左边为空,把parent的左边接上cur的右边
                parent.left=cur.right;
            }else{//cur为要删除元素并且走到了parent右边，cur左边为空，把parent的右边接上cur的右边
                parent.right=cur.right;
            }
        } else if (cur.right == null) {//以cur为根右树为空的情况
            if(cur==root){
                root=cur.left;
            }else if(cur==parent.left){
                parent.left=cur.left;
            }else{
                parent.right=cur.left;
            }
        }else{//cur左右都不为空的情况************
            TreeNode targetParent = cur;
            TreeNode target = cur.left;
            while(target.right!=null){
                targetParent = target;
                target = target.right;
            }
            cur.val=target.val;
            if(target==targetParent.right){
                targetParent.right=target.left;
            }else{
                targetParent.left=target.left;
            }
        }
    }
}
